<template>
  <div class="course-list-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">课程中心</h1>
        <p class="page-subtitle">发现优质课程，开启学习之旅</p>
      </div>
      
      <!-- 搜索栏 -->
      <div class="search-section">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索课程名称、讲师或关键词"
          size="large"
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button type="primary" @click="handleSearch">
              搜索
            </el-button>
          </template>
        </el-input>
      </div>
    </div>
    
    <!-- 筛选和排序 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-select
          v-model="searchForm.category"
          placeholder="课程分类"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
        
        <el-select
          v-model="searchForm.level"
          placeholder="难度等级"
          clearable
          @change="handleSearch"
        >
          <el-option label="入门" value="beginner" />
          <el-option label="进阶" value="intermediate" />
          <el-option label="高级" value="advanced" />
        </el-select>
        
        <el-select
          v-model="searchForm.price"
          placeholder="价格筛选"
          clearable
          @change="handleSearch"
        >
          <el-option label="免费" value="free" />
          <el-option label="付费" value="paid" />
        </el-select>
        
        <el-button
          v-if="hasActiveFilters"
          type="info"
          plain
          @click="clearFilters"
        >
          清除筛选
        </el-button>
      </div>
      
      <div class="filter-right">
        <el-radio-group
          v-model="searchForm.sort"
          @change="handleSearch"
        >
          <el-radio-button label="latest">最新</el-radio-button>
          <el-radio-button label="popular">最热</el-radio-button>
          <el-radio-button label="rating">评分</el-radio-button>
          <el-radio-button label="price">价格</el-radio-button>
        </el-radio-group>
        
        <el-button-group class="view-mode">
          <el-button
            :type="viewMode === 'grid' ? 'primary' : 'default'"
            @click="viewMode = 'grid'"
          >
            <el-icon><Grid /></el-icon>
          </el-button>
          <el-button
            :type="viewMode === 'list' ? 'primary' : 'default'"
            @click="viewMode = 'list'"
          >
            <el-icon><List /></el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>
    
    <!-- 课程列表 -->
    <div class="course-content">
      <el-row v-if="viewMode === 'grid'" :gutter="24">
        <el-col
          v-for="course in courseList"
          :key="course.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="6"
        >
          <CourseCard
            :course="course"
            @click="handleCourseClick(course)"
            @favorite="handleFavorite"
            @enroll="handleEnroll"
          />
        </el-col>
      </el-row>
      
      <div v-else class="course-list-view">
        <CourseListItem
          v-for="course in courseList"
          :key="course.id"
          :course="course"
          @click="handleCourseClick(course)"
          @favorite="handleFavorite"
          @enroll="handleEnroll"
        />
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="8" animated />
      </div>
      
      <!-- 空状态 -->
      <el-empty
        v-if="!loading && courseList.length === 0"
        description="暂无课程数据"
        class="empty-state"
      >
        <el-button type="primary" @click="handleSearch">刷新</el-button>
      </el-empty>
    </div>
    
    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="total"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Grid, List } from '@element-plus/icons-vue'
import CourseCard from '@/components/course/CourseCard.vue'
import CourseListItem from '@/components/course/CourseListItem.vue'
import { getCourseList, getCategories, enrollCourse, favoriteCourse } from '@/api/course'
import { useUserStore } from '@/store/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const courseList = ref([])
const categories = ref([])
const total = ref(0)
const viewMode = ref('grid')

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category: '',
  level: '',
  price: '',
  sort: 'latest'
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 24
})

// 计算属性
const hasActiveFilters = computed(() => {
  return searchForm.category || searchForm.level || searchForm.price
})

// 获取课程列表
const fetchCourseList = async () => {
  try {
    loading.value = true
    
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    
    // 移除空值
    Object.keys(params).forEach(key => {
      if (!params[key]) {
        delete params[key]
      }
    })
    
    const response = await getCourseList(params)
    
    courseList.value = response.data.list || []
    total.value = response.data.total || 0
    
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 获取课程分类
const fetchCategories = async () => {
  try {
    const response = await getCategories()
    categories.value = response.data || []
  } catch (error) {
    console.error('获取课程分类失败:', error)
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  fetchCourseList()
}

// 清除筛选
const clearFilters = () => {
  searchForm.category = ''
  searchForm.level = ''
  searchForm.price = ''
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchCourseList()
}

// 页码改变
const handlePageChange = (page) => {
  pagination.page = page
  fetchCourseList()
  
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 课程点击
const handleCourseClick = (course) => {
  router.push(`/course/${course.id}`)
}

// 收藏课程
const handleFavorite = async (courseId, isFavorite) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/auth/login')
    return
  }
  
  try {
    await favoriteCourse(courseId, isFavorite)
    
    // 更新本地数据
    const course = courseList.value.find(c => c.id === courseId)
    if (course) {
      course.isFavorite = isFavorite
      course.favoriteCount += isFavorite ? 1 : -1
    }
    
    ElMessage.success(isFavorite ? '收藏成功' : '取消收藏成功')
    
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 报名课程
const handleEnroll = async (courseId) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/auth/login')
    return
  }
  
  try {
    await enrollCourse(courseId)
    
    // 更新本地数据
    const course = courseList.value.find(c => c.id === courseId)
    if (course) {
      course.isEnrolled = true
      course.enrollCount += 1
    }
    
    ElMessage.success('报名成功')
    
  } catch (error) {
    console.error('报名失败:', error)
    ElMessage.error(error.message || '报名失败，请重试')
  }
}

// 初始化页面参数
const initPageParams = () => {
  const query = route.query
  
  if (query.keyword) searchForm.keyword = query.keyword
  if (query.category) searchForm.category = query.category
  if (query.level) searchForm.level = query.level
  if (query.price) searchForm.price = query.price
  if (query.sort) searchForm.sort = query.sort
  if (query.page) pagination.page = parseInt(query.page)
  if (query.size) pagination.size = parseInt(query.size)
}

// 更新URL参数
const updateUrlParams = () => {
  const query = {
    ...searchForm,
    page: pagination.page,
    size: pagination.size
  }
  
  // 移除空值
  Object.keys(query).forEach(key => {
    if (!query[key] || (key === 'page' && query[key] === 1) || (key === 'size' && query[key] === 24)) {
      delete query[key]
    }
  })
  
  router.replace({ query })
}

// 监听搜索参数变化
watch(
  () => [searchForm, pagination.page, pagination.size],
  () => {
    updateUrlParams()
  },
  { deep: true }
)

// 组件挂载
onMounted(() => {
  initPageParams()
  fetchCategories()
  fetchCourseList()
})
</script>

<style lang="scss" scoped>
.course-list-container {
  padding: var(--spacing-lg);
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: var(--spacing-xxxl);
  padding: var(--spacing-xxxl) 0;
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light-2) 100%);
  border-radius: var(--border-radius-base);
  color: white;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="dots" width="20" height="20" patternUnits="userSpaceOnUse"><circle cx="10" cy="10" r="1" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23dots)"/></svg>') repeat;
  }
}

.header-content {
  position: relative;
  z-index: 1;
  margin-bottom: var(--spacing-xl);
}

.page-title {
  font-size: 2.5rem;
  font-weight: 600;
  margin-bottom: var(--spacing-sm);
}

.page-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
}

.search-section {
  position: relative;
  z-index: 1;
  max-width: 600px;
  margin: 0 auto;
  
  .search-input {
    --el-input-height: 50px;
    
    :deep(.el-input__wrapper) {
      border-radius: 25px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    :deep(.el-input-group__append) {
      border-radius: 0 25px 25px 0;
    }
  }
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-xl);
  padding: var(--spacing-lg);
  background: var(--bg-color);
  border-radius: var(--border-radius-base);
  box-shadow: var(--box-shadow-light);
}

.filter-left {
  display: flex;
  gap: var(--spacing-md);
  align-items: center;
  flex-wrap: wrap;
  
  .el-select {
    width: 140px;
  }
}

.filter-right {
  display: flex;
  gap: var(--spacing-md);
  align-items: center;
}

.view-mode {
  .el-button {
    padding: 8px 12px;
  }
}

.course-content {
  margin-bottom: var(--spacing-xxxl);
}

.course-list-view {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.loading-container {
  padding: var(--spacing-xl);
}

.empty-state {
  padding: var(--spacing-xxxl);
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: var(--spacing-xl) 0;
}

// 响应式设计
@include respond-below(lg) {
  .filter-section {
    flex-direction: column;
    gap: var(--spacing-lg);
    align-items: stretch;
  }
  
  .filter-left,
  .filter-right {
    justify-content: center;
  }
}

@include respond-below(md) {
  .course-list-container {
    padding: var(--spacing-md);
  }
  
  .page-header {
    padding: var(--spacing-xl) var(--spacing-lg);
  }
  
  .page-title {
    font-size: 2rem;
  }
  
  .filter-left {
    flex-direction: column;
    align-items: stretch;
    
    .el-select {
      width: 100%;
    }
  }
  
  .filter-right {
    flex-direction: column;
    align-items: stretch;
    
    .el-radio-group {
      justify-content: center;
    }
  }
}

@include respond-below(sm) {
  .page-header {
    padding: var(--spacing-lg);
  }
  
  .page-title {
    font-size: 1.5rem;
  }
  
  .search-section {
    .search-input {
      --el-input-height: 44px;
      
      :deep(.el-input__wrapper) {
        border-radius: 22px;
      }
      
      :deep(.el-input-group__append) {
        border-radius: 0 22px 22px 0;
      }
    }
  }
  
  .filter-section {
    padding: var(--spacing-md);
  }
  
  .pagination-container {
    :deep(.el-pagination) {
      justify-content: center;
      flex-wrap: wrap;
    }
  }
}
</style>